import React, { useState, useEffect } from "react";
import { Table, message, Button, Tag, Modal, notification } from "antd";
import { useNavigate } from "react-router";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import axios from "axios";

// 草稿箱中只展示 编辑状态的新闻auditState===0
export default function AuditList() {
  const [auditList, setAuditList] = useState([]);
  const { username } = JSON.parse(localStorage.getItem("token"));
  const navigate = useNavigate();
  const { confirm } = Modal;
  const colorList = ["yellow", "orange", "green", "red"];
  const auditStateList = ["未审核", "审核中", "已通过", "未通过"];
  useEffect(() => {
    // _ne=0 不等于0  _lte=1  小于等于1
    axios
      .get(
        `http://localhost:5000/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`
      )
      .then((res) => {
        setAuditList(res.data);
      })
      .catch(() => {
        message.warning("获取审核列表失败！");
      });
  }, [username]);
  // 撤销
  const handelRemove = (item) => {
    confirm({
      title: "确认撤销吗？",
      icon: <ExclamationCircleOutlined />,
      async onOk() {
        try {
          setAuditList(auditList.filter((data) => data.id !== item.id));
          await axios.patch(`http://localhost:5000/news/${item.id}`, {
            auditState: 0,
          });
          console.log(1);
          message.success("撤销成功,您可以到草稿箱中查看");
        } catch (error) {
          message.error("撤销失败");
        }
      },
      onCancel() {
        message.warning("取消撤销");
      },
    });
  };
  // 更新
  const handelUpdate = (item) => {
    // 更新 只需跳转到更新页面即可  即和草稿箱的编辑项类似
    navigate(`/news-manage/update/${item.id}`);
  };
  // 发布
  const handlePublish = (item) => {
    axios
      .patch(`http://localhost:5000/news/${item.id}`, {
        publishState: 2,
        createTime: new Date().getTime(),
      })
      .then(() => {
        navigate("/publish-manage/published");
        // 成功后的消息通知
        notification.open({
          message: "通知",
          description: "您可以到发布管理中的已发布中查看该新闻",
          duration: 5,
          placement: "bottomRight",
        });
      })
      .catch(() => {
        message.error("发布失败");
      });
  };
  const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render: (title, item) => {
        return (
          <a href={`http://localhost:3000/#/news-manage/preview/${item.id}`}>
            {title}
          </a>
        );
      },
    },
    {
      title: "新闻分类",
      dataIndex: "category",
      render: (category) => {
        return category.title;
      },
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    {
      title: "审核状态",
      dataIndex: "auditState",
      render: (auditState) => {
        return (
          <div>
            <Tag color={colorList[auditState]}>
              {auditStateList[auditState]}
            </Tag>
          </div>
        );
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            {item.auditState === 1 && (
              <Button
                danger
                onClick={() => {
                  handelRemove(item);
                }}
              >
                撤销
              </Button>
            )}
            {item.auditState === 2 && (
              <Button
                type="primary"
                onClick={() => {
                  handlePublish(item);
                }}
              >
                {" "}
                发布
              </Button>
            )}
            {item.auditState === 3 && (
              <Button
                color="orange"
                onClick={() => {
                  handelUpdate(item);
                }}
              >
                {" "}
                更新
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  return (
    <Table
      dataSource={auditList}
      columns={columns}
      rowKey={(item) => item.id}
      pagination={{ pageSize: 5 }}
    />
  );
}
